import { baseRequestClient, requestClient } from '#/api/request';
import { useAccessStore } from '@vben/stores';


export namespace AuthApi {
  /** 登录接口参数 */
  export interface LoginParams {
    username: string;
    password: string;
  }

  /** 登录接口返回值 */
  export interface LoginResult {
    accessToken: string;
    refreshToken: string;
    expiresAt: string;
    user: {
      id: string;
      userName: string;
      email: string;
      phoneNumber: string | null;
      roles: string[];
    }
  }

  // 根据后端 RefreshTokenRequestDto 定义请求类型
  export interface RefreshTokenRequest {
    accessToken: string;    // 过期的访问令牌
    refreshToken: string;   // 有效的刷新令牌
  }

  // 根据后端 TokenResponseDto 定义响应类型
  export interface RefreshTokenResult {
    data: string;          // 新的访问令牌
    status: number;        // 状态码
    refreshToken: string;  // 刷新令牌
  }
}

/**
 * 登录
 */
export async function loginApi(data: AuthApi.LoginParams) {
  return requestClient.post<AuthApi.LoginResult>('/auth/login', data);
}

/**
 * 刷新访问令牌
 */
export async function refreshTokenApi() {
  const accessStore = useAccessStore();

  return requestClient.post<AuthApi.RefreshTokenResult>(
    '/auth/refresh-token',
    {
      accessToken: accessStore.accessToken,
      refreshToken: accessStore.refreshToken,
    } as AuthApi.RefreshTokenRequest
  );
}

/**
 * 退出登录
 */
export async function logoutApi() {
  return requestClient.post('/auth/logout');
}

/**
 * 获取用户权限码
 */
export async function getAccessCodesApi() {
  // 这里返回一个空数组即可 TODO: 需要修改
  return [];
  // return requestClient.get<string[]>('/auth/codes');
}

// 注册请求参数类型
export interface RegisterParams {
  username: string;
  password: string;
  confirmPassword: string;
}

// 注册响应类型
export interface RegisterResult {
  status: number;
  data: {
    userId: string;
    username: string;
  };
}

/**
 * 用户注册
 */
export async function registerApi(params: RegisterParams) {
  return baseRequestClient.post<RegisterResult>('/auth/register', params);
}

// 密码重置请求类型
export interface InitiatePasswordResetParams {
  account: string;
  resetType: 1 | 2;
}

// 密码重置响应类型
export interface InitiatePasswordResetResult {
  status: number;
  data: boolean;
  message: string;
}

/**
 * 发起密码重置
 * @param params 重置参数
 */
export async function initiatePasswordResetApi(params: InitiatePasswordResetParams) {
  return baseRequestClient.post<InitiatePasswordResetResult>('/auth/reset-password/initiate', params);
}

// 验证密码重置请求参数类型
export interface ValidatePasswordResetParams {
  token: string;
  newPassword: string;
  resetType: 1 | 2; // 1: Email, 2: SMS
}

// 密码重置响应类型
export interface ValidatePasswordResetResult {
  status: number;
  data: boolean;
  message: string;
}

/**
 * 验证并重置密码
 * @param params 重置参数
 */
export async function validatePasswordResetApi(params: ValidatePasswordResetParams) {
  return baseRequestClient.post<ValidatePasswordResetResult>('/auth/reset-password/validate', params);
}
